package com.demo.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.constant.Constant;
import com.demo.entity.DvtDiagnose;
import com.demo.entity.Message;
import com.demo.entity.Patient;
import com.demo.entity.User;
import com.demo.entity.Vo.MessageSocketVo;
import com.demo.enums.DvtDiagnoseResultEnum;
import com.demo.enums.MessageRemindEnum;
import com.demo.enums.MessageSourceEnum;
import com.demo.enums.PreventiveDiagnoseOpportunityEnum;
import com.demo.jwt.JwtTokenUtil;
import com.demo.mapper.DvtDiagnoseMapper;
import com.demo.mapper.PatientMapper;
import com.demo.mapper.UserMapper;
import com.demo.response.Result;
import com.demo.schedule.regular.RegularMindSchedule;
import com.demo.service.IDvtDiagnoseService;
import com.demo.service.IMessageService;
import com.demo.util.HeatUtil;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * dvt诊断表 服务实现类
 *
 * @author zm
 * @since 2020-12
 */
@Service
@Slf4j
public class DvtDiagnoseServiceImpl extends ServiceImpl<DvtDiagnoseMapper, DvtDiagnose> implements IDvtDiagnoseService {
    @Resource
    DvtDiagnoseMapper dvtDiagnoseMapper;
    @Resource
    UserMapper userMapper;
    @Resource
    PatientMapper patientMapper;
    @Autowired
    IMessageService messageService;

    /**
     * 新增dvt诊断评估
     *
     * @param dvtDiagnose 实体对象
     */
    @Override
    public Result addDvtDiagnose(DvtDiagnose dvtDiagnose) throws Exception {
        //DVt临床可能性为低度
        dvtDiagnose.setDiagnoseResult(DvtDiagnoseResultEnum.DIAGNOSE_IN.getValue());
        save(dvtDiagnose);
        return Result.success(dvtDiagnose.getDvtDiagnoseId());
    }

    /**
     * 编辑dvt诊断评估
     *
     * @param dvtDiagnose 实体对象
     * @return
     */
    @Override
    public Result updateDvtDiagnose(DvtDiagnose dvtDiagnose) throws Exception {
        if (dvtDiagnose.getUpdatedUserId() == null || dvtDiagnose.getDvtDiagnoseId() == null) {
            return Result.error(Constant.KEY_ID);
        }
        updateById(dvtDiagnose);
        return Result.success();
    }

    /**
     * 删除dvt诊断评估
     *
     * @param deletedUserId 删除人ID
     * @param dvtDiagnoseId 诊断评估ID
     * @return
     */
    @Override
    public Result deleteDvtDiagnose(Integer deletedUserId, Integer dvtDiagnoseId) {
        DvtDiagnose dvtDiagnose = new DvtDiagnose();
        dvtDiagnose.setDeletedUserId(deletedUserId);
        dvtDiagnose.setDvtDiagnoseId(dvtDiagnoseId);
        dvtDiagnose.setDeletedTime(new Date());
        boolean flag = updateById(dvtDiagnose);
        if (flag == false) {
            return Result.error(Constant.DB_ERROR);
        }
        return Result.success();
    }

    /**
     * 查询dvt诊断评估
     *
     * @param pageNumber 页码
     * @param pageSize   大小
     * @param patientId  病患序列号
     * @param dvtItemId  预置字段---*暂时不使用
     * @return
     */
    @Override
    public Result dvtDiagnoseList(Integer pageNumber, Integer pageSize, Integer patientId, Integer dvtItemId) {
        IPage<DvtDiagnose> page = new Page<>(pageNumber, pageSize);
        QueryWrapper<DvtDiagnose> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(patientId != null, "patient_id", patientId);
        queryWrapper.isNull("deleted_user_id");
        queryWrapper.orderByDesc("dvt_diagnose_id");
        page = dvtDiagnoseMapper.selectPage(page, queryWrapper);

        for (DvtDiagnose record : page.getRecords()) {
            User user = userMapper.selectById(record.getSignUserId());
            if (user != null) {
                record.setSignUserName(user.getUserTrueName());
            }
        }
        PageInfo<DvtDiagnose> pageInfo = new PageInfo<>(page.getRecords());
        pageInfo.setPages((int) page.getPages());
        pageInfo.setTotal(page.getTotal());
        if (pageNumber.equals(page.getPages())) {
            pageInfo.setIsLastPage(false);
        } else {
            pageInfo.setIsLastPage(true);
        }
        return Result.success(pageInfo);
    }

    /**
     * @param dvtDiagnoseId 主键ID
     * @param signUserId
     * @param userPass      密码
     */
    @Override
    public void doctorsSignatureVte(Integer dvtDiagnoseId, Integer signUserId, String userPass) throws Exception {
        //当前登录用户可能是医生，护士等。
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        Integer uid = JwtTokenUtil.decodeTokenUserId(request.getHeader("token"));
        User user = userMapper.getUserByPass(uid, HeatUtil.md5(userPass));
        if (user == null) {
            throw new Exception("密码错误");
        }

        //签字
        DvtDiagnose diagnose = dvtDiagnoseMapper.selectById(dvtDiagnoseId);
        if (StrUtil.isEmpty(diagnose.getDetectAdvise()) && StrUtil.isEmpty(diagnose.getDetectConsider())) {
            throw new Exception("诊断未完成，签字失败");
        }
        diagnose.setSignTime(new Date());
        diagnose.setSignUserId(uid);
        diagnose.setDiagnoseResult(DvtDiagnoseResultEnum.DIAGNOSE_FINISH.getValue());
        int i = dvtDiagnoseMapper.updateById(diagnose);
        if (i == 1 && diagnose.getDiagnoseOpportunity().intValue() == PreventiveDiagnoseOpportunityEnum.DING_QI.getValue()) {
            if (diagnose != null) {
                //添加定时消息提醒
                RegularMindSchedule.addDvtTask(diagnose);
            }
        }

    }

    @Override
    public Result getDvtPreventiveInterval() throws Exception {
        List<MessageSocketVo> messageList = dvtDiagnoseMapper.getDvtPreventiveIntervalDay(7);
        try {
            for (MessageSocketVo messageSocketVo : messageList) {
                QueryWrapper<Message> messageQueryWrapper = new QueryWrapper();
                messageQueryWrapper.select(new String[]{"created_time"});
                messageQueryWrapper.eq("message_source_sn", messageSocketVo.getMessageSourceSn());
                messageQueryWrapper.eq("message_source", 2);
                messageQueryWrapper.eq("message_status", 0);
                messageQueryWrapper.eq("message_type", 2);
                messageQueryWrapper.orderByDesc("message_id");
                messageQueryWrapper.last("limit 1");
                Message messageIn = messageService.getOne(messageQueryWrapper);
                DateTime dateTime = DateUtil.parse(DateUtil.now(), "yyyy-MM-dd HH:mm:ss");
                Patient patient = patientMapper.selectById(messageSocketVo.getPrientId());
                Map<String, Object> msgContent = new HashMap<>();
                msgContent.put("bed_id", patient.getBedId());
                msgContent.put("bed_name", patient.getBedName());
                msgContent.put("patient_name", patient.getPatientName());
                msgContent.put("dept_name", patient.getDeptName());
                msgContent.put("dept_sn", patient.getDeptSn());
                if (messageIn != null) {
                    log.info("相差时间{}", Long.valueOf(DateUtil.between(dateTime, messageIn.getCreatedTime(), DateUnit.DAY)));
                    if (DateUtil.between(dateTime, messageIn.getCreatedTime(), DateUnit.DAY) > 1L) ;
                    msgContent.put("message_text", "上次处置建议为“一周后复查超声检查”，建议重新进行 DVT 筛查");
                    messageService.sendMessageNotification(MessageRemindEnum.ZHEN_DUAN_REMIND, patient, MessageSourceEnum.OTHER, msgContent, 0);
                    continue;
                }
                msgContent.put("message_text", "上次处置建议为“一周后复查超声检查”，建议重新进行 DVT 筛查");
                messageService.sendMessageNotification(MessageRemindEnum.ZHEN_DUAN_REMIND, patient, MessageSourceEnum.OTHER, msgContent, 0);
            }
        } catch (Exception e) {
            log.error("定时消息错误{}", e);
        }
        return Result.success(messageList);
    }

    @Override
    public Result getDvtRankByDeptSn(String orderType, Integer topNumber) {
        return Result.success(dvtDiagnoseMapper.getDvtRankByDeptSn(orderType, topNumber));
    }

}
